package com.kob.backend.config.filter;

import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 设定请求头的参数
        String token = request.getHeader("Authorization");

        // 注意有空格哟
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从第八位开始截取后面的token字符串
        token = token.substring(7);

        String userid;
        try {
            // 解析token， claims存放解析后的字符串
            Claims claims = JwtUtil.parseJWT(token);
            //  从claims中获取用户用户id字符串
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 从数据库中获取用户
        User user = userMapper.selectById(Integer.parseInt(userid));

        // 没有该用户，则抛出异常
        if (user == null) {
            throw new RuntimeException("用户名未登录");
        }

        // 封装user对象，springsecurity使用该对象来进行认证和授权
        UserDetailsImpl loginUser = new UserDetailsImpl(user);
        // 使用springsecurity中的UsernamePasswordAuthenticationToken（用户密码认证）来进一步封装userDetail对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);

        // 加入到SpringSecurity框架
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
